package com.zprmb.udzt.gesture;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat.AuthenticationResult;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zprmb.udzt.BbtApplication;
import com.zprmb.udzt.CustomDialog_view_new;
import com.zprmb.udzt.GeActivity;
import com.zprmb.udzt.MainActivity;
import com.zprmb.udzt.R;
import com.zprmb.udzt.gesture.GestureDrawline.GestureCallBack;
import com.zprmb.udzt.util.CustomDialog;
import com.zprmb.udzt.util.FingerPrintHelp;
import com.zprmb.udzt.util.FingerPrintHelp.OnCallBackListenr;
import com.zprmb.udzt.util.FingerSetting;
import com.zprmb.udzt.util.FingerprintUtil;
import com.zprmb.udzt.util.MySharePreferenceUtil;
import com.zprmb.udzt.view.StatusBarUtil;


/**
 * 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟矫斤拷锟斤拷
 */
public class GestureEditActivity extends GeActivity implements OnClickListener {
    /**
     * 锟街伙拷锟斤拷锟�/ public static final String PARAM_PHONE_NUMBER =
     * "PARAM_PHONE_NUMBER"; /** 锟斤拷图
     */
    static final String PARAM_INTENT_CODE = "PARAM_INTENT_CODE";
    /**
     * 锟阶达拷锟斤拷示锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟诫，锟斤拷锟斤拷选锟斤拷锟斤拷锟�
     */
    public static final String PARAM_IS_FIRST_ADVICE = "PARAM_IS_FIRST_ADVICE";
    private TextView mTextTitle;
    private TextView mTextCancel;
    private LockIndicator mLockIndicator;
    private TextView mTextTip;
    private FrameLayout mGestureContainer;
    private GestureContentView mGestureContentView;
    private TextView mTextReset;
    private String mParamSetUpcode = null;
    private String mParamPhoneNumber;
    private boolean mIsFirstInput = true;
    private String mFirstPassword = null;
    private String mConfirmPassword = null;
    private int mParamIntentCode;
    private RelativeLayout rl_gesture;
    private RelativeLayout top_layout;
    private SharedPreferences sha;
    private CustomDialog.Builder mDialog;
    private CustomDialog_view_new.Builder builder;
    KeyguardManager keyguardManager = (KeyguardManager) BbtApplication.getContext().getSystemService(BbtApplication.getContext().KEYGUARD_SERVICE);
    CustomDialog.Builder customDialog;
    StatusBarUtil statusBarUtil;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gesture_edit);
        setImmersionStatus();
        statusBarUtil=new StatusBarUtil();

//		checkPermission();
        setUpViews();
        setUpListeners();
        BbtApplication.getInstance().addActvity(this);
        if (getIntent().getStringExtra("from").equals("login")) {
            mTextTip.setText("为了您的账户安全,请设置手势密码");
            mTextReset.setText("暂不设置");
            top_layout.setVisibility(View.INVISIBLE);
        }



    }


    // 普通申请一个权限
    private void checkPermission() {


        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED

                || ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
            requestPermission(0);
        }
//        PermissionUtils.checkAndRequestPermission(mContext, PERMISSION_CAMERA2, REQUEST_CODE_CAMERA,
//                new PermissionUtils.PermissionRequestSuccessCallBack() {
//                    @Override
//                    public void onHasPermission() {
//                        // 权限已被授予
////                        toCamera();
//                    }
//                });
    }

    private final int REQUEST_CODE_CAMERA = 1, REQUEST_CODE_PERMISSIONS = 2;
    private final String[] PERMISSIONS = new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.USE_FINGERPRINT};
    private AlertDialog alertDialog;

    //	private AlertDialog alertDialog1;
    private void requestPermission(int permission) {

        ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);

    }

    private boolean requestPermissionState = false;
    int zhiwen;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        return false;
    }

    private void setImmersionStatus() {
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    @SuppressLint("NewApi")
    private void setUpViews() {
        mTextTitle = (TextView) findViewById(R.id.text_title);
        mTextCancel = (TextView) findViewById(R.id.text_cancel);
        mTextReset = (TextView) findViewById(R.id.text_reset);
        rl_gesture = (RelativeLayout) findViewById(R.id.rl_gesture);
        top_layout = (RelativeLayout) findViewById(R.id.top_layout);
        mTextReset.setClickable(false);
        sha = getSharedPreferences("config", MODE_PRIVATE);
        zhiwen = sha.getInt("finger", 0);
        mLockIndicator = (LockIndicator) findViewById(R.id.lock_indicator);
        mTextTip = (TextView) findViewById(R.id.text_tip);
        mGestureContainer = (FrameLayout) findViewById(R.id.gesture_container);
//		rl_gesture.setBackground(new BitmapDrawable(BitmapUtils.readBitMap(
//				GestureEditActivity.this, R.drawable.shoushi)));
        // 锟斤拷始锟斤拷一锟斤拷锟斤拷示锟斤拷锟斤拷锟斤拷锟絭iewGroup
        mGestureContentView = new GestureContentView(this, false, "",
                new GestureCallBack() {
                    @Override
                    public void onGestureCodeInput(String inputCode) {
                        if (!isInputPassValidate(inputCode)) {
                            mTextTip.setText(Html
                                    .fromHtml("<font color='#c70c1e'>最少链接4个点, 请重新输入</font>"));
                            mGestureContentView.clearDrawlineState(0L);
                            return;
                        }
                        if (mIsFirstInput) {
                            mFirstPassword = inputCode;
                            updateCodeList(inputCode);
                            mGestureContentView.clearDrawlineState(0L);
                            mTextReset.setClickable(true);
                            mTextReset
                                    .setText("重新设置");
                            mTextTip.setText("再次绘制解锁图案");
                        } else {
                            if (inputCode.equals(mFirstPassword)) {
                                Toast.makeText(GestureEditActivity.this,
                                        "设置成功", Toast.LENGTH_SHORT).show();
                                mGestureContentView.clearDrawlineState(0L);
                                MySharePreferenceUtil.put(GestureEditActivity.this, "shoushi", "1");
                                MySharePreferenceUtil.put(GestureEditActivity.this, "gesture", "1");

                                Editor editor = sha.edit();
                                editor.putString(
                                        sha.getString("mobile", "123456"),
                                        inputCode);
                                editor.putInt("ge", 1);
                                editor.putBoolean("isTouth", false);
                                editor.commit();
                                Intent intent = new Intent();

                                intent.putExtra("second", "I am second!");
                                setResult(0, intent);
                                if (getIntent().getIntExtra("update", 0) == 1) {
                                    finish();
                                    return;
                                }
                                if (getIntent().getStringExtra("towhere")
                                        .equals("main")) {


                                    Log.d("zhiwenzhiwen", zhiwen + "");

                                    if (sha.getInt("finger", 0) == 1) {
                                        showDialog();
                                    } else {
                                        MySharePreferenceUtil.put(GestureEditActivity.this, "zhiwendenglu", 0 + "");
                                        startMainActivity();
                                    }

                                    return;
                                }
                                // GestureEditActivity.this.finish();
                            } else {

                                mTextTip.setText(Html
                                        .fromHtml("<font color='#c70c1e'>两次绘制不一致，请重新绘制</font>"));
                                // 锟斤拷锟斤拷锟狡讹拷锟斤拷锟斤拷
                                Animation shakeAnimation = AnimationUtils
                                        .loadAnimation(
                                                GestureEditActivity.this,
                                                R.anim.shake);
                                mTextTip.startAnimation(shakeAnimation);
                                // 锟斤拷锟街伙拷锟狡碉拷锟竭ｏ拷1.5锟斤拷锟斤拷锟斤拷
                                mGestureContentView.clearDrawlineState(1300L);
                            }
                        }
                        mIsFirstInput = false;
                    }

                    @Override
                    public void checkedSuccess() {

                    }

                    @Override
                    public void checkedFail() {

                    }
                });
        // 锟斤拷锟斤拷锟斤拷锟狡斤拷锟斤拷锟斤拷示锟斤拷锟侥革拷锟斤拷锟斤拷锟斤拷锟斤拷
        mGestureContentView.setParentView(mGestureContainer);
        updateCodeList("");
    }

    private void setUpListeners() {
        mTextCancel.setOnClickListener(this);
        mTextReset.setOnClickListener(this);
    }

    private void updateCodeList(String inputCode) {
        // 锟斤拷锟斤拷选锟斤拷锟酵硷拷锟�
        mLockIndicator.setPath(inputCode);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (customDialog != null && customDialog.create().isShowing()) {

            if (keyguardManager.isKeyguardSecure()) {
                customDialog.create().dismiss();
                onFingerprint(null);
            }
        }
        /*	if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)
                || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)
				|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
				|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CALL_PHONE)
				|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.USE_FINGERPRINT)) {
			requestPermission(0);


		}*/
    }

    private void showDialog() {
        mDialog = new CustomDialog.Builder(GestureEditActivity.this);

        mDialog.setMessage("手势密码设置成功，是否启用指纹解锁");
        mDialog.create().setCancelable(false);
        mDialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                onFingerprintClick(null);

            }
        });
        mDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

                Editor editor = sha.edit();
                editor.putInt(getMobile() + "openfinger", 0);
                editor.commit();
                MySharePreferenceUtil.put(GestureEditActivity.this, "zhiwendenglu", 0 + "");
                startMainActivity();
            }
        });
        mDialog.create().show();
    }

    public void onFingerprintClick(View v) {

        FingerPrintHelp.callFingerPrint(new OnCallBackListenr() {

            @Override
            public void onSupportsuccess() {
                // TODO Auto-generated method stub

            }

            @Override
            public void onSupportFailed() {
                // TODO Auto-generated method stub

            }

            @Override
            public void onInsecurity() {
                // TODO Auto-generated method stub
//			FingerSetting.openFingerPrintSettingPage(GestureEditActivity.this);
//			FingerprintUtil.cancel();
                mDialog.create().dismiss();
                customDialog = new CustomDialog.Builder(GestureEditActivity.this);

                customDialog.setMessage("请在系统设置中开启指纹功能");
                customDialog.create().setCancelable(false);
                customDialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        FingerSetting.openFingerPrintSettingPage(GestureEditActivity.this);

                    }
                });
                customDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        customDialog.create().dismiss();
                        startMainActivity();

                    }
                });
                customDialog.create().show();


            }

            @Override
            public void onFInsecurity() {
                // TODO Auto-generated method stub
                mDialog.create().dismiss();
                onFingerprint(null);


            }

            @Override
            public void onEnrollFailed() {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAuthenticationSucceeded(AuthenticationResult result) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAuthenticationStart() {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAuthenticationFailed() {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAuthenticationError(int errMsgId, CharSequence errString) {
                // TODO Auto-generated method stub

            }
        });
    }

    private void startMainActivity() {
//        if (MainActivity.instance != null) {
//            MainActivity.instance.finish();
//        }

        MySharePreferenceUtil.put(GestureEditActivity.this, "newintentflag", "1");
        if (zhiwen == 0) {
            Log.e("mTextReset","mTextReset2");

            MySharePreferenceUtil.put(GestureEditActivity.this, "zhiwen", "2");
            Intent intent1 = new Intent(GestureEditActivity.this,
                    MainActivity.class);

            startActivity(intent1);
        } else {
            Log.e("mTextReset","mTextReset3");

            MySharePreferenceUtil.put(GestureEditActivity.this, "zhiwen", "1");
            Intent intent1 = new Intent(GestureEditActivity.this,
                    MainActivity.class);

            startActivity(intent1);
        }

        finish();
//	}

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text_cancel:
                this.finish();
                break;
            case R.id.text_reset:
                if (mTextReset.getText().toString().equals("暂不设置")) {
                    Log.e("mTextReset","mTextReset");
                    MySharePreferenceUtil.put(GestureEditActivity.this, "gesture", "0");
                    startMainActivity();
                    return;
                }
                mIsFirstInput = true;
                updateCodeList("");
                mTextTip.setText(getString(R.string.set_gesture_pattern));
                mTextReset.setText("暂不设置");
                break;
            default:
                break;
        }
    }

    public void onFingerprint(View v) {

        FingerprintUtil.callFingerPrint(new FingerprintUtil.OnCallBackListenr() {

            @Override
            public void onSupportFailed() {
                showToast("当前设备不支持指纹");
            }

            @Override
            public void onInsecurity() {

            }

            @Override
            public void onEnrollFailed() {
                showToast("请到设置中设置指纹");
            }

            @Override
            public void onAuthenticationStart() {
                Log.e("start", "finger_start");
                builder = new CustomDialog_view_new.Builder(GestureEditActivity.this);
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        FingerprintUtil.cancel();
                        builder.create().dismiss();
                        startMainActivity();
                    }
                });
                builder.setMessage("请验证已有手机指纹");
//                builder.setMessage2("请验证已有手机指纹");
                builder.create().setCancelable(false);
                builder.create().show();
            }

            @Override
            public void onAuthenticationError(int errMsgId, CharSequence errString) {
                showToast(errString.toString());
//            Log.e("dialog", builder.create()+"");

            }

            @Override
            public void onAuthenticationFailed() {
                showToast("认证失败");
            }

            @Override
            public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
                showToast(helpString.toString());
            }

            @Override
            public void onAuthenticationSucceeded(AuthenticationResult result) {
                showToast("认证成功");
                Log.e("start", "finger_success");
                if (builder.create() != null) {
                    builder.create().mdissmis();
                    Editor editor = sha.edit();
                    editor.putInt(getMobile() + "openfinger", 1);
                    editor.commit();
                    MySharePreferenceUtil.put(GestureEditActivity.this, "zhiwendenglu", 1 + "");


                    startMainActivity();
                }

            }
        });
    }

    private boolean isInputPassValidate(String inputPassword) {
        if (TextUtils.isEmpty(inputPassword) || inputPassword.length() < 4) {
            return false;
        }
        return true;
    }

}

